package com.huixuebao.api.controller.login;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.huixuebao.api.dto.InsuredOrderShortDTO;
import com.huixuebao.api.entity.BaseDivision;
import com.huixuebao.api.entity.CaptchaEntity;
import com.huixuebao.api.service.BaseDivisionService;
import com.huixuebao.api.service.CaptchaService;
import com.huixuebao.api.service.rpc.InsureOrderService;
import com.huixuebao.api.service.rpc.UserService;
import com.huixuebao.api.dto.UserDTO;
import com.huixuebao.api.util.CaptchaUtil;
import com.huixuebao.api.util.JWTUtils;
import com.huixuebao.api.util.SendSms;
import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.api.util.RedisUtil;
import com.huixuebao.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 * @author ft_yu
 * @version 1.0
 * @date 2020-11-11 22:04
 */
@Slf4j
@RestController()
@RequestMapping("/app")
public class AppController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    UserService userService;

    @Autowired
    CaptchaService captchaService;

    @Autowired
    InsureOrderService insureOrderSerivce;

    @Autowired
    BaseDivisionService baseDivisionService;

    /**
     *<p>Title: checkMobile</p>
     *<p>Description:手机号登陆</p>
     */
    @PostMapping("/login")
    public ApiResult<Map<Object,Object>> login(@RequestParam String phone, @RequestParam String smsCode) throws JsonProcessingException {

        ApiResult<UserDTO> apiResult = userService.getUserByPhone(phone);
        HashMap<String, String> payload = new HashMap<>();
        payload.put("phone",phone);
        payload.put("smsCode",smsCode);
        String jwtToken = JWTUtils.getToken(payload);
        ApiResult<Map<Object,Object>> stringApiResult = new ApiResult<>();
        if (apiResult.isSuccess()) {
            UserDTO userDTO = apiResult.getData();
            Map<Object, Object> mapData = new HashMap<>();
            boolean result = validateSmsCode(phone, smsCode);
            if (result) {
                redisUtil.set(jwtToken, JsonUtil.getStringData(userDTO));
                mapData.put("id",userDTO.getId());
                mapData.put("token",jwtToken);
                stringApiResult.setData(mapData);
                return stringApiResult;
            } else {
                log.info("验证码验证失败");
                stringApiResult.setData(mapData);
                stringApiResult.setSuccess(false);
                stringApiResult.setMessage("验证码验证失败");
                return stringApiResult;
            }
        } else {
            stringApiResult.setSuccess(false);
            stringApiResult.setMessage("用户不存在");
            return stringApiResult;
        }
    }

    /**
     * @author fatao_yu
     * 获取短信验证码
     * @param phone
     * @return
     */
    @RequestMapping(value = "/getSmsCode",method = RequestMethod.GET)
    public ApiResult getSmsCode(@RequestParam String phone)throws JsonProcessingException {
        /**
         * 获取用户手机号码，根据手机号码进行发送验证码
         */
        ApiResult<UserDTO> apiResult = userService.getUserByPhone(phone);
        if (!apiResult.isSuccess()) {
            log.error("该用户未投保 phone={}", phone);
            apiResult.setMessage("该用户未投保");
            return apiResult;
        }
        String smsCode = CaptchaUtil.getPhoneVerifyCode();
        SendSms.sendCaptchaCode(phone,smsCode);
        CaptchaEntity captcha = new CaptchaEntity();
        captcha.setCaptchaType(CaptchaUtil.CAPTCHA_TYPE_MOBILE);
        captcha.setCaptchaValue(smsCode);
        captcha.setCreateTime(new Date());
        captcha.setPhone(phone);
        apiResult.setData(null);
        captchaService.save(captcha);
        return apiResult;
    }

    /**
     * @author fatao_yu
     * 短信验证码
     * @param phone
     * @param smsCode
     * @return
     */
    private boolean validateSmsCode(String phone, String smsCode) {
        List<CaptchaEntity> list = captchaService.get(phone, smsCode);
        if (CollUtil.isNotEmpty(list)) {
            return true;
        }
        return false;
    }
    /**
     * @author fatao_yu
     * 根据userId进行查询投保信息
     * @param phone
     * @return
     */
    @GetMapping("/userorders")
    public ApiResult<List<InsuredOrderShortDTO>> getInsureOrders(@RequestParam("phone") String phone) {
        return insureOrderSerivce.listInsuredOrders(phone);
    }
    /**
     * 获取地区码（暂没用）
     * @param pid
     * @return
     */
    @GetMapping("/list")
    public ApiResult<List<BaseDivision>> list(String pid){
        return baseDivisionService.queryDivisionByPid(pid);
    }

    /**
     * 获取地区码
     * @param
     * @return
     */
    @PostMapping("/buildAreaTree")
    public ApiResult buildAreaTree(){
        return baseDivisionService.buildAreaTree();
    }

    @PostMapping("/updateStattleState")
    public ApiResult updateStattleState(@RequestParam("policyId") String policyId){

        return insureOrderSerivce.updateSettleState(policyId);
    }
}